package test;

import com.alibaba.fastjson2.JSONObject;
import com.rabbitmq.client.Channel;
import io.github.loserYa.log.handler.SaveLogHandler;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.env.Environment;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 日志落地
 *
 * @author java
 * @date 2022/6/13 11:05
 */
@Component
public class BizLogSaveConsumer extends SaveLogHandler {

    @Resource
    private SaveLogMapper saveLogMapper;

    public BizLogSaveConsumer(ConfigurableListableBeanFactory factory, Environment environment) {
        super(factory, environment);
    }

    @Override
    public String getPre() {
        return "log";
    }

    @RabbitListener(containerFactory = "logContainerFactory",
            // 绑定队列
            bindings = {
                    // 绑定队列的类
                    @QueueBinding(
                            // 1.队列名称
                            value = @Queue(name = "MQ_LOG_QUEUE"),
                            // 消息交换器 1.交换器名称，2.交换器类型
                            exchange = @Exchange(value = "MQ_LOG_EXCHANGE", type = ExchangeTypes.FANOUT))}, concurrency = "30")
    @Override
    public void bizLogSave(@Payload JSONObject msg, @Headers Map<String, Object> headers, Channel channel) throws IOException {

        long deliveryTag = (long) headers.get(AmqpHeaders.DELIVERY_TAG);
        try {
            List<String> list = buildSql(msg);
            for (String sql : list) {
                if (StringUtils.isEmpty(sql)) {
                    return;
                }
                saveLogMapper.execSql(sql);
                System.out.println("format SQL : " + sql + System.lineSeparator());
            }
        } catch (Exception e) {
            log.error("BizLogSaveConsumer.bizLogSave.error", e);
        } finally {
            channel.basicAck(deliveryTag, false);
        }

    }

}
